/*
** main.c for  in /home/gomes_m//rattrapage/server
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Tue Jul 23 12:17:17 2013 mickael gomes
** Last update Sat Jul 27 14:45:47 2013 mickael gomes
*/

#include		<stdio.h>
#include		<stdlib.h>
#include		"struct.h"
#include		"prototypes.h"

void			get_socket_max(t_socket *socket, t_list *list)
{
  t_list		*tmp;
  int			max = 0;

  tmp = list;
  while (tmp != NULL)
    {
      if (tmp->fd > max)
	max = tmp->fd;
      tmp = tmp->next;
   }
  socket->fds_max = max + 1;
}

char			*check_port_validity(char *port)
{
  int			i = 0;

  while (port[i])
    {
      if (port[i] < '0' || port[i] > '9')
	my_putstr(2, "Syntax error : Port\n", 1);
      i++;
    }
  return (port);
}

void			show_list(t_list *list)
{
  t_list	        *tmp;

  tmp = list;
  while (tmp->next != NULL)
    {
      printf("Client -> n°%d\n", tmp->fd);
      tmp = tmp->next;
    }
}

int			main(int ac, char **av, char **env)
{
  t_list		*list;
  t_list		*tmp;
  t_list		*save;
  t_socket		socket;

  if (ac != 2)
    my_putstr(2, "One argument is required.\n[USAGE] port\n", 1);
  init_socket(&socket, xatoi(check_port_validity(av[1])));
  list = xmalloc(sizeof(*list));
  tmp = xmalloc(sizeof(*list));
  init_list(list, env);
  init_tmp(tmp);
  save = list;
  my_cd(tmp);
  while (12)
    {
      check_new_client(&socket, list);
      get_socket_max(&socket, save);
      check_event(save, &socket);
      if (list->fd > 0)
	list = list->next;
      check_disconnected(&save);
    }
  return (EXIT_SUCCESS);
}
